package com.fiberhome.opticalbox.view.third.image;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.Handler;
import android.util.AttributeSet;

import com.fiberhome.opticalbox.utils.LogUtil;

/**
 * 
 * @author wangpeng
 * @date 2015-01-07
 */
public class PercentImageView extends BaseImageView {

	private final float START_ANGLE = 133f;
	private final float TOTAL_ANGLE = 275f;
	private float currAngle = 0;
	private float tmpAngle;
	private float endAngle;

	private final long INTERVAL = 20;

	private Handler handler = new Handler();

	public PercentImageView(Context context) {
		this(context, null);
	}

	public PercentImageView(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
	}

	public PercentImageView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}

	public Bitmap getBitmap(int width, int height) {
		Bitmap bitmap = Bitmap.createBitmap(width, height, Config.ARGB_8888);
		Canvas canvas = new Canvas(bitmap);
		final Paint paint = new Paint();
		final Rect rect = new Rect(0, 0, width, height);
		final RectF rectF = new RectF(rect);
		paint.setAntiAlias(true);

		canvas.drawArc(rectF, START_ANGLE, currAngle, true, paint);

		paint.setXfermode(new android.graphics.PorterDuffXfermode(Mode.SRC_IN));
		canvas.drawBitmap(bitmap, 0, 0, paint);

		return bitmap;
	}

	public void resetCurrAngle() {
		currAngle = 0;
	}

	public void setCurrentPercent(float currentPercent) {
		currAngle = TOTAL_ANGLE * (currentPercent / 100);
		postInvalidate();
	}

	public void setCurrentPercentByAnim(float currentPercent) {
		handler.removeCallbacks(runnable);
		endAngle = TOTAL_ANGLE * (currentPercent / 100);
		if (endAngle < currAngle) {
			return;
		}
		tmpAngle = (endAngle - currAngle) / 15;

		handler.post(runnable);
	}

	private Runnable runnable = new Runnable() {
		@Override
		public void run() {
			currAngle = currAngle + tmpAngle;
			if (currAngle > endAngle) {
				currAngle = endAngle;
			}
			LogUtil.i("angle:" + currAngle + ",tmpAngle:" + tmpAngle + ",endAngle:" + endAngle);
			invalidate();
			if (currAngle < endAngle) {
				handler.postDelayed(runnable, INTERVAL);
			}
		}
	};

	@Override
	public Bitmap getBitmap() {
		return getBitmap(getWidth(), getHeight());
	}
}
